/**
 * 选择支付方式
 */

import React, { Component } from 'react'
import {
  View, Text, StyleSheet, Image, TouchableOpacity, TextInput,StatusBar,Keyboard,TouchableWithoutFeedback
} from 'react-native'
import NavPage from '../../common/NavPage'
import SafeView from 'react-native-safe-area-view'
import moment from 'moment'
import axios from 'axios'
import qs from 'qs'
import Screen from '../../common/screen'
import Toast from 'antd-mobile/lib/toast'
import ImageResources from '../../common/ImageResources'
import FetchResources from '../../common/FetchResources'
import GetSetStorge from '../../common/GetSetStorge'
import FilterPage from '../../common/FilterPage'
import QRCode from 'react-native-qrcode'
// import * as WeChat from 'react-native-wechat'
import Alipay from '../../common/Alipay'
// import BackgroundTimer from 'react-native-background-timer'
import { RouteHelper } from 'react-navigation-easy-helper'

export default class SellTicket extends Component{
  constructor(props) {
    super(props)
    let { consumptionName,consumptionId,price,userType,ticketNumber,needPay } = this.props.navigation.state.params
    this.state = {
      payWay:1,
      price:needPay == 'freeTicket' ? 0 : price,
      total:needPay == 'freeTicket' ? 0 : price,
      maxNumber:needPay == 'freeTicket' ? 1 : 10,//最大可购票数
      cash:0,
      number:1,
      subBottom:0,
      addBottom:0,
      butSub:'SubDisable',
      butAdd:'Add',
      consumptionName:consumptionName||'',
      consumptionId:consumptionId||'',
      userType:userType|| 2 ,
      saller:'',
      ticketNumber:ticketNumber||'',
      needPay:needPay,
      animatedHeight:(Screen.height - 280)*0.5,
      payUrl:'',
      weChatPayUrl:'',
      payId:'',
      checkPermission:'',
      orderTime:'',
      code:'',
      state:'',
      weChatMsg:''

    }
  }

  componentDidMount() {
    // Toast.loading('加载中...', 0)
    GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
      if (result) {
        this.setState({saller:result.split('|')[0]})
      }
    }).catch((error) => {
      console.log('==========================')
      console.log('系统异常' + error)
      console.log('==========================')
    })
  }

  componentWillMount () {  
    //监听键盘弹出事件  
    this.keyboardDidShowListener = Keyboard.addListener(  
      "keyboardDidShow",  
      this.keyboardDidShowHandler.bind(this)  
    )
    //监听键盘隐藏事件  
    this.keyboardDidHideListener = Keyboard.addListener(  
      "keyboardDidHide",  
      this.keyboardDidHideHandler.bind(this)  
    ) 
  }  
    
  componentWillUnmount() {  
    Toast.hide()
    this.timer && clearInterval(this.timer)
    //卸载键盘弹出事件监听  
    if (this.keyboardDidShowListener != null) {  
        this.keyboardDidShowListener.remove();  
    }  
    //卸载键盘隐藏事件监听  
    if (this.keyboardDidHideListener != null) {  
        this.keyboardDidHideListener.remove();  
    }  
  }   

  //键盘弹出事件响应  
  keyboardDidShowHandler(event) {  
    this.setState({ KeyboardShown: true });  
  }  

  //键盘隐藏事件响应  
  keyboardDidHideHandler(event) {  
    this.setState({ KeyboardShown: false });  
  }  

  lostBlur(){  
    //退出软件盘  
    let { number } = this.state
    if(number == null || number == ''){
      this.setState({number:1})
    }
    Keyboard.dismiss();    
  } 



  goBack() {
    RouteHelper.pop()
  }

  next(){
    let {consumptionName,consumptionId,total,price,number,payWay,saller,userType,ticketNumber,payUrl} = this.state
    
    let url = FetchResources.Fetch.PlaceOrder
    if(payWay == '1'){
      url = FetchResources.Fetch.WxOrder
    }else if(payWay == '3'){
      url = FetchResources.Fetch.PlaceOrder
    }
    axios.post(url,//购票接口
			qs.stringify({
				consumptionId,
        singlePrice: price,
        num:number,
				saller,
        ticketNo: ticketNumber,
				userType,
				payWay,
			})
		).then((response) => {
      if(response.data.success){//查询成功
        if(payWay == '1'){//微信支付
          let {url,payId} = response.data.data
          this.setState({payUrl:url,payId},()=>{
            this.weChatToPay()
          })

        }else{
          let {payWay, code, state, orderTime} = response.data.data.order
          response.data.data.checkPermission == '1' ?
          RouteHelper.navigate('PaySuccess',{consumptionName,consumptionId,total,price,number,payWay,code,state,orderTime,checkPermission:true}): 
          RouteHelper.navigate('PaySuccess',{consumptionName,consumptionId,total,price,number,payWay,code,state,orderTime,checkPermission:false})
        }
      }else{
        
      }
		}).catch((error) => {
      Toast.hide()
    })

  }


  weChatToPay(){
    Toast.loading('生成微信付款码...', 0)
    let { payUrl } = this.state
    axios.post(payUrl,//微信支付接口
		).then((response) => {
      if(response.data.data.return_code == 'SUCCESS'){//查询成功
        let {checkPermission,order} = response.data.orderData
        let {orderTime,code,consumptionId,orderId,totalPrice,singlePrice,leftNum,payWay,state} = order
        this.setState({weChatPayUrl:response.data.data.code_url,checkPermission,orderTime,code,state,payWay},()=>{
          Toast.hide()
          this.showFilter()
          this.timer1 = setTimeout(() => {
            this.payResult()
          }, 2000)
          this.timer = setInterval(() => {
            this.payResult()
          }, 2000)

        })
      }else{
        
      }
		}).catch((error) => {
    })
  }

  //轮询 查询支付结果
  payResult(){
    let {payId} = this.state
    axios.post(FetchResources.Fetch.PayResult,//微信支付接口
      qs.stringify({
				payId
			})
		).then((response) => {
      if(response.data.success){//查询成功
        if(response.data.state == '3'){ //支付成功
          Toast.success('支付成功',1)
          this.timer2 = setTimeout(() => {
            this.setState({weChatMsg:response.data.msg},()=>{
              this.PaySuccess()
            })
          }, 1000)
          this.timer && clearInterval(this.timer)
          this.hideFilter()
        }else if(response.data.state == '1'){//未支付
          // this.hideFilter()
          // this.timer && clearInterval(this.timer)
          // Toast.info('未支付',1)
        }
      }else{
        
      }
		}).catch((error) => {
    })
  }

  PaySuccess(){
    let {consumptionName,consumptionId,total,price,number,payWay,orderTime,checkPermission,code,state} = this.state
    checkPermission == '1' ?
    RouteHelper.navigate('PaySuccess',{consumptionName,consumptionId,total,price,number,payWay,code,state,orderTime,checkPermission:true}):
    RouteHelper.navigate('PaySuccess',{consumptionName,consumptionId,total,price,number,payWay,code,state,orderTime,checkPermission:false})
  }

  showFilter() {
		this.filterPage.show()
	}

	hideFilter() {
    this.filterPage.hide()
    this.timer && clearInterval(this.timer)
  }

  addSubtract(type){
    this.lostBlur()
    let { number } = this.state
    if(number == null || number == ''){
      this.setState({number:1},()=>{
        this.addSub(type)
      })
    }else{
      this.addSub(type)
    }
  }

  addSub(type){
    let { number,total,price,maxNumber} = this.state
    if(type == 'add'){
      if(this.state.number < maxNumber){
        this.setState({
          number:parseInt(number)+1,
          total : price * (parseInt(number)+1),
          addBottom:0,
          butAdd:'AddActived',
          butSub:'Sub'
        })
        this.timer = setTimeout(() => {
          this.setState({addBottom:0,butAdd:'Add'})
        }, 300)
      }else{
        this.setState({
          butAdd:'AddDisable'
        })
      }
      
    }else{
      if(this.state.number>1){
        this.setState({
          number:parseInt(number)-1,
          total : price * (parseInt(number)-1),
          subBottom:0,
          butSub:'SubActived',
          butAdd:'Add'
        })
        this.timer = setTimeout(() => {
          this.setState({subBottom:0,butSub:'Sub'})
        }, 300)
      }else{
        this.setState({
          butSub:'SubDisable'
        })
      }
    }
  }

  render() {
    let { payWay, total,cash,number,price,maxNumber,butSub,butAdd,consumptionName ,animatedHeight,weChatPayUrl} = this.state

    return (
      <SafeView style={styles.container} forceInset={{ top: 'never' }} >
        <StatusBar
          animated={true}
          hidden={false}
          backgroundColor={'#111'}
          translucent={true}
          barStyle={'light-content'}
          showHideTransition={'fade'}
          networkActivityIndicatorVisible={true}
        />

        <NavPage goBack={this.goBack.bind(this)} title={''} refund={true} showGoBack={true} bgColor={'#F6F7F8'} />
        <TouchableWithoutFeedback onPress={this.lostBlur.bind(this)}>
        <View style={{flex:1}}>
          <View style={styles.goodsBox}>
            <Text style={{fontSize:24,color:'#111',fontWeight:'500',textAlign:'left',marginLeft:10,marginBottom:10}}>{consumptionName}</Text>
            <View style={{flex:1,justifyContent: 'center',alignItems:'center',borderRadius:5}}>
              <View style={{flex:1,flexDirection:'column',justifyContent: 'center',alignItems:'center',backgroundColor:'#fff',width:Screen.width*0.9,borderRadius:5,padding:10}}>
                <View style={{height:30,flexDirection:'row',paddingHorizontal:4}}>
                  <Text style={{flex:1,fontSize:16}}>价格</Text>
                  <Text style={{flex:1,textAlign:'right',fontSize:16}}>数量</Text>
                </View>

                <View style={{flex:1,flexDirection:'row',}}>
                  <Text style={{flex:2,fontSize:32,color:'#FF9700',fontWeight:'500'}}>￥{total}</Text>
                  <View style={{flex:1.5,flexDirection:'row',justifyContent: 'flex-end',alignItems:'center',height:45}}>
                    <TouchableOpacity activeOpacity={0.5} onPress={this.addSubtract.bind(this,'subtraction')} >
                      <Image style={[{width:40,height:40,padding:0,marginBottom:this.state.subBottom}]} source={number == 1 ?ImageResources.PayIcon['SubDisable'] : ImageResources.PayIcon[butSub]}  />
                    </TouchableOpacity>
                    <TextInput
                      placeholder=""
                      underlineColorAndroid="transparent"
                      keyboardType={'numeric'}
                      returnKeyType={'next'}
                      // onSubmitEditing={this.lostBlur()}
                      maxLength={11}
                      placeholderTextColor='#ccc'
                      style={{width:32,paddingBottom:4,textAlign:'center'}}
                      value={`${number}`}
                      // defaultValue={`${number}`}
                      onChangeText={(number) => number == ''|| number == null || number == NaN ? this.setState({total:price,number:''}) : ( number <= maxNumber ? this.setState({ number,total:price*parseInt(number) }) : this.setState({ number : maxNumber , total:price*maxNumber }) ) }
                    />
                    <TouchableOpacity activeOpacity={0.5} onPress={this.addSubtract.bind(this,'add')} >
                      <Image style={[{width:40,height:40,marginBottom:this.state.addBottom}]} source={number == maxNumber ?ImageResources.PayIcon['AddDisable'] : ImageResources.PayIcon[butAdd]}  />
                    </TouchableOpacity>
                  </View>
                </View>

              </View>
            </View>
          </View>

          <View style={{padding:10}}>
            <Text style={{fontSize:24,color:'#111',fontWeight:'500',textAlign:'left',marginLeft:10,marginBottom:10}}>付款方式</Text>
            <View style={{justifyContent: 'center',alignItems:'center',borderRadius:5,width:Screen.width*0.9,marginLeft:Screen.width*0.05-10,}}>
              <TouchableOpacity activeOpacity={0.8} onPress={() => { this.setState({ payWay: 1 }),this.lostBlur() }} style={styles.item}>
                <Image style={styles.icon} source={ImageResources.PayIcon.WechatPay} />
                <Text style={{ flex: 1,fontSize:16 }}>微信支付</Text>
                <Image source={payWay === 1 ? ImageResources.CommonIcon.Checked : ImageResources.CommonIcon.Uncheck} style={styles.selectIcon} />
              </TouchableOpacity>

              {/* <TouchableOpacity activeOpacity={0.8} onPress={() => { this.setState({ payWay: 2 }),this.lostBlur() }} style={[styles.item]}>
                <Image style={styles.icon} source={ImageResources.PayIcon.Ali} />
                <Text style={{ flex: 1,fontSize:16 }}>支付宝支付</Text>
                <Image source={payWay === 2 ? ImageResources.CommonIcon.Checked : ImageResources.CommonIcon.Uncheck} style={styles.selectIcon} />
              </TouchableOpacity> */}

              <TouchableOpacity activeOpacity={0.8} onPress={() => { this.setState({ payWay: 3 }),this.lostBlur() }} style={styles.item}>
                <Image style={styles.icon} source={ImageResources.PayIcon.Balance} />
                <Text style={{ flex: 1 ,fontSize:16}}>现金支付</Text>
                <Image source={payWay === 3 ? ImageResources.CommonIcon.Checked : ImageResources.CommonIcon.Uncheck} style={styles.selectIcon} />
              </TouchableOpacity>
            </View>
          </View>
          
          <View style={{flex:1,justifyContent: 'center',alignItems:'center'}}>
            <TouchableOpacity onPress={this.next.bind(this)} style={{justifyContent: 'center',alignItems:'center'}} >
              <View style={{justifyContent: 'center',alignItems:'center'}}>
                  <Image  source={ImageResources.PayIcon.Pay} style={{height:80,width:298}}  />
              </View>
            </TouchableOpacity> 
          </View>
        </View>
        </TouchableWithoutFeedback>

        <FilterPage
					containerHeight={Screen.height}
					modalBoxHeight={300}
          modalBoxTop={0}
          modalBoxWidth={Screen.width * 0.70}
          animatedHeight={animatedHeight}
          modalBoxMarginLeft={Screen.width * 0.15}
          ref={ref => this.filterPage = ref}
          hidePosition={''}
				>
          <View style={{ backgroundColor:'#F6F7F8', padding: 10, borderRadius: 8, alignItems: 'center', width: Screen.width * 0.70, position: 'relative', height:300}}>
            <Text  style={{ color: '#111', fontSize: 20 }} >请出示微信扫码支付</Text>
            {/* <View style={{ flexDirection: 'row', height: Screen.height, flex: 1, alignItems: 'center', justifyContent: 'center', paddingBottom: 5, paddingTop: 20, width: Screen.width * 0.7, flexWrap: 'wrap',}}> */}
              <View style={{flex:1,justifyContent: 'center',alignItems:'center'}}>
                <QRCode
                  value={weChatPayUrl}
                  size={200}
                  bgColor="#000"
                  fgColor="#F6F7F8"
                />
              {/* </View> */}
            </View>
            <TouchableOpacity onPress={this.hideFilter.bind(this)} style={{height:30,justifyContent: 'center',alignItems:'center'}} >
              <Text style={{paddingHorizontal:20,paddingVertical:4,color:'#aaa',fontSize:16,backgroundColor:'#ccc',borderRadius:4,textAlign:'right'}}>取消</Text>
            </TouchableOpacity>
          </View>
          
        </FilterPage>


      </SafeView>
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F6F7F8'
  },
  goodsBox:{
    height:150,
    borderRadius:4,
    padding:10
  },
  buttons:{
    fontSize: 16,
    textAlign:'center',
    width:25,
    height:25,
    borderColor:'#bbb',
    borderRadius:12.5,
    borderStyle:'solid',
    borderWidth:1,
  },
  item: {
    height:68,
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingHorizontal: 10,
    marginBottom:10,
    flexDirection: 'row',
    borderRadius:5
  },
  yue: {
    padding: 20,
    alignItems: 'center'
  },
  txt: {
    borderWidth: 1,
    borderColor: '#eee',
    width: Screen.width * 0.5,
    height: 40,
    paddingHorizontal: 10,
    marginBottom: 10
  },
  icon: {
    width: 35,
    height: 30,
    marginRight: 10,
  },
  selectIcon: {
    width: 17,
    height: 17
  },
  foot: {
    height: 45,
    flexDirection: 'row',
    width: Screen.width,
    backgroundColor: '#fff'
  },
  footLeft: {
    width: Screen.width * 0.6,
    flexDirection: 'row',
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingLeft: 20
  },
  footRight: {
    backgroundColor: '#52B45D',
    width: Screen.width * 0.4,
    justifyContent: 'center',
    alignItems: 'center'
  }
})